package com.heima.gateway.app.filter;

import com.heima.gateway.app.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import org.apache.commons.lang.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 自定义的全局过滤器
 * GlobalFilter全局过滤器的接口
 * Ordered执行顺序的接口
 */
@Component
public class MyAuthFilter implements GlobalFilter, Ordered {
    /**
     * 执行过滤的方法
     * @param exchange  交换机，里面可以获取相对应的请求对象和响应对象及上下文
     * @param chain 过滤器链的意思
     * @return
     */
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        //1.获取请求对象和响应对象
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        //2.判断当前请求是否是登录请求
        String path = request.getURI().getPath();
        if(path.contains("/login/login_auth")){
            //3.如果是登录请求，则放行
           return chain.filter(exchange);
        }

        //4.如果不是登录请求，则判断请求头中是否有token
        String token = request.getHeaders().getFirst("token");

        //5.如果没有token,则报401，没有权限
        if(StringUtils.isBlank(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //6.如果有token,则校验token是否有效
        Claims claimsBody = AppJwtUtil.getClaimsBody(token);
        int i = AppJwtUtil.verifyToken(claimsBody);
        if(i==1 || i==2){
            //7.如果token无效，则报401，没有权限
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }

        //8。如果token有效，则放行
        return chain.filter(exchange);
    }

    /**
     * 执行顺序的的方法，返回值越小，则优先级越高
     * @return
     */
    @Override
    public int getOrder() {
        return 0;
    }
}
